<template>
  <div class="app-container">
    <div class="top">
      <el-input
        v-model="kwInput"
        placeholder="输入内容进行筛选"
        class="input-with-select"
        clearable
        @keyup.native.enter="handleSearch"
      >
        <el-select slot="prepend" v-model="selected_projects" placeholder="指定项目" collapse-tags multiple>
          <el-option
            v-for="item in projects"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>

        <el-button slot="append" icon="el-icon-search" :disabled="!searchAvailable" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button
        type="primary"
        class="el-icon-plus add-btn"
        @click="handleAction('create', {'type': 'supplier', 'name': '添加供应商'}, 'supplier')"
      >添加供应商
      </el-button>

    </div>

    <tree-table
      v-loading="treeLoading"
      :data="data"
      :eval-func="func"
      :expand-all="expandAll"
      border
      fit
      highlight-current-row
      style="width: 100%"
      element-loading-text="给我一点时间"
    >

      <el-table-column label="信息" align="center" width="280">
        <template slot-scope="scope">
          <div v-if="scope.row.type === 'supplier'"><span>站点:{{ scope.row.site }} | 电话:{{ scope.row.tel }}</span></div>
          <div v-else-if="scope.row.type === 'catalog'">名称:{{ scope.row.name }}</div>
        </template>
      </el-table-column>

      <el-table-column label="项目属性" align="center" width="350">
        <template slot-scope="scope">
          <el-select
            v-if="scope.row.type === 'supplier'"
            v-model="scope.row.project_id"
            size="mini"
            placeholder="无"
            @change="handleProjectChange(scope.row)"
          >
            <el-option
              v-for="item in projects"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-button
            v-if="scope.row.type==='supplier'"
            slot="reference"
            size="mini"
            type="success"
            plain
            style="margin-left:20px"
            :disabled="!scope.row.project_id"
            icon="el-icon-eye"
            @click="handleProjectAttrPreview(scope.row.project_id)"
          >查看
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="400" align="center" class-name="small-padding fiexed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleAction('view', scope.row)">查看</el-button>
          <el-button size="mini" type="success" plain @click="handleAction('edit', scope.row)">修改</el-button>
          <el-button size="mini" type="danger" plain @click="handleAction('delete', scope.row)">删除</el-button>
          <el-button size="mini" type="primary" plain @click="handleAction('create', scope.row, 'catalog')">添加目录
          </el-button>
          <el-tooltip v-if="scope.row.type === 'catalog'" class="item" effect="dark" content="产品管理" placement="bottom">
            <el-button size="mini" plain @click="toUpload(scope.row.id)">
              <svg-icon icon-class="product-manage" />
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </tree-table>

    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <supplier
      :model="supplier_form_data"
      :action="supplierAction"
      :dialog-title="dialogTitle"
      :dialog-form-visible="supplierFormVisible"
      @reload="reload"
      @cancelDialog="cancelSupplierDialog($event)"
    />

    <catalog
      :model="catalog_form_data"
      :action="catalogAction"
      :dialog-title="dialogTitle"
      :dialog-form-visible="catalogFormVisible"
      @reload="reload"
      @cancelDialog="cancelCatalogDialog($event)"
    />

    <el-dialog
      title="项目属性"
      :visible.sync="projectDialogVisible"
      width="50%"
    >
      <el-table :data="projectDialogData">
        <el-table-column align="center" width="100" prop="id" label="id" />
        <el-table-column align="center" width="300" prop="name" label="键" />
        <el-table-column align="center" prop="value" label="值" />
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import treeTable from '@/components/TreeTable'
import treeToArray from './treeTable/customEval'
import supplier from './elements/supplier'
import catalog from './elements/catalog'

import { Get, ShowProjectAttr } from '@/api/erp/elicink/project'
import { GetTree, Put } from '@/api/erp/elicink/supplier'

const qs = require('qs')
const axios = require('axios')

const MtTypeOptions = {
  supplier: '供应商',
  catalog: '目录'
}

export default {
  name: 'ResourceManage',
  components: { supplier, treeTable, catalog },
  filters: {
    typeFilter(type) {
      return MtTypeOptions[type]
    }
  },
  data() {
    return {
      dialogTitle: '',
      // supplier dialog
      supplier_form_data: null,
      supplierFormVisible: false,
      supplierAction: null,
      // catalog dialog
      catalog_form_data: null,
      catalogFormVisible: false,
      catalogAction: null,
      // 项目 选择器 数据源
      projects: [],
      // input
      kwInput: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      searchAvailable: true,
      // 选中的 供应商id
      selected_projects: [],
      // talbe 数据源
      data: [],
      // table loading
      treeLoading: false,
      MtTypeOptions,
      func: treeToArray,
      expandAll: false,

      // 项目属性查看
      projectDialogVisible: false,
      projectDialogData: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.treeLoading = true
      this.searchAvailable = false

      axios.all([GetTree(qs.stringify({
        stop: 'catalog',
        kw: this.kwInput,
        project_ids: this.selected_projects
      }, { arrayFormat: 'repeat' })), Get()])
        .then(axios.spread((tree, projects) => {
          this.data = tree.data
          this.total = tree.total
          this.projects = projects.data.data
          this.treeLoading = false
          this.searchAvailable = true
        })).catch(err => {
          console.log(err)
          this.treeLoading = false
          this.searchAvailable = true
        })
    },
    handleAction(action, row, _) {
      console.log(8888888, action, row, _)
      switch (action) {
        case 'delete':
          this.dialogTitle = ['确认要删除 [', MtTypeOptions[row.type], '] ', row.name, ' 的所有内容?'].join('')
          break
        case 'view':
          this.dialogTitle = ['查看 ', MtTypeOptions[row.type], ' —— ', row.name].join('')
          break
        case 'edit':
          this.dialogTitle = ['修改 ', MtTypeOptions[row.type], ' —— ', row.name].join('')
          break
        case 'create':/* 特殊处理, 根据 _ 判断行为 */
          if (_ === 'supplier') {
            this.dialogTitle = '添加供应商'
            this.supplierAction = action
            this.supplierFormVisible = true
            this.supplier_form_data = row
          } else if (_ === 'catalog') {
            this.dialogTitle = '添加目录'
            this.catalogAction = action
            this.catalogFormVisible = true
            this.catalog_form_data = row
          }
          return
      }
      switch (row.type) {
        case 'supplier':
          this.supplierAction = action
          this.supplierFormVisible = true
          this.supplier_form_data = row
          break
        case 'catalog':
          this.catalogAction = action
          this.catalogFormVisible = true
          this.catalog_form_data = row
          break
      }
    },
    cancelSupplierDialog(v) {
      this.supplierFormVisible = v
    },
    cancelCatalogDialog(v) {
      this.catalogFormVisible = v
    },
    reload() {
      this.getList()
    },
    toUpload(cid) {
      this.$router.push({ name: 'erp.productManage', params: { c_id: cid }, query: { t: +new Date() }})
    },
    handleProjectChange(v) {
      Put(v.id, { project_id: v.project_id })
        .then(response => {
          this.getList()
        })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    // 模板属性预览
    handleProjectAttrPreview(v) {
      this.projectDialogData = []
      this.projectDialogVisible = true
      ShowProjectAttr(v)
        .then(response => {
          this.projectDialogData = response.data
        })
    }
  }
}
</script>

<style scoped>
  .top >>> .el-select .el-input {
      width: 350px;
    }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top >>> .el-input-group__append .el-button--default {
    color: white;
    background-color: #409EFF;
    border: 1px solid #409eef;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
    margin-top: 28px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 130px
  }
  .mt-pagination {
    float: right;
    margin-top: 5px;
  }
</style>
